package com.keya.device;

import com.keya.base.exception.BusinessException;
import com.keya.base.output.PageData;
import io.micrometer.core.annotation.Timed;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/device")
@Timed("api_device")
public class DeviceController {

    @Resource
    DeviceService deviceService;

    @PutMapping("/host")
    public Device updateHost(@RequestBody Device device) throws Exception {
        return deviceService.updateLocalHost(device.getAetitle(), device.getName());
    }

    @GetMapping("/host")
    public Device getHost() throws Exception {
        return deviceService.getLocalHost();
    }

    @PostMapping("/")
    public Device insertDevice(@RequestBody Device device) throws Exception {
        return deviceService.insert(device);
    }

    @PutMapping("/")
    public Device updateDevice(@RequestBody Device device) {
        return deviceService.update(device);
    }

    @GetMapping("/{id}")
    public Device getDevice(@PathVariable("id") Integer id) {
        return deviceService.getById(id);
    }

    @GetMapping("/list")
    public PageData list(@RequestParam(required = false, name = "type") String type) throws BusinessException {
        if (StringUtils.isNotEmpty(type)) {
            List<Device> devices = deviceService.listByType(type);
            return PageData.build((long) devices.size(), devices);
        }
        return PageData.build((long) deviceService.typeNotNullCount(), deviceService.listDevices());
    }

    @DeleteMapping("/{id}")
    public void deleteDevice(@PathVariable("id") Integer id) {
        deviceService.removeById(id);
    }

    @GetMapping("/test/{id}")
    public void test(@PathVariable("id") Integer id) throws Exception {
        String error = deviceService.testByAetitle(id);
        if (error != null) {
            throw new Exception(error);
        }
    }
}
